<template>
  <a-drawer
    v-model:open="visible"
    title="接口文档管理"
    width="100%"
    @cancel="visible = false"
  >
    <div class="content">
      <a-space class="toolbar">
        <a-button type="primary" @click="handleNew">新增</a-button>
      </a-space>
      <div class="flex items-wrap">
        <a-card :title="item.name" v-for="item in app.items.value" class="item-card">
          <template #extra>
            <a-space>
              <a-button type="primary" v-if="item.editing" @click="handleSave(item)">保存</a-button>
              <a-button danger v-if="item.editing" @click="handleCancel(item)">取消</a-button>
              <a-button type="primary" v-if="!item.editing" @click="handleEdit(item)">编辑</a-button>
              <a-button type="primary" danger v-if="!item.editing" @click="handleDelete(item)">删除</a-button>
            </a-space>
          </template>
          <custom-form
            :form-data="item"
            :columns="columns"
            :editing="item.editing"
          >
          </custom-form>
          <a-space>
            <a-button type="primary" class="btn-ok" @click="handleSelect(item)">选择</a-button>
          </a-space>
        </a-card>
      </div>
    </div>
  </a-drawer>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import useState from '@/utils/useState';
import { useStore } from 'vuex';
import { ApiDocItem, IAppState } from '@/store/app-types';
import CustomForm from './Form/CustomForm.vue';

const app: any = useState({
  items: (state: any) => (state.app as IAppState).items,
})
const $store = useStore()

var visible = ref(false)
var columns = reactive([
  {
    field: 'title',
    title: '标题名称'
  },
  {
    field: 'url',
    title: 'URL地址',
    type: 'textarea'
  },
  {
    field: 'controllersDir',
    title: '控制器路径'
  },
  {
    field: 'definitionsDir',
    title: '实体定义路径'
  }
])

var $emit = defineEmits(['select'])

function handleNew() {
  $store.dispatch('app/addItem', {})
}

function handleSave(item: ApiDocItem) {
  $store.dispatch('app/saveItem', item)
}

function handleCancel(item: ApiDocItem) {
  if(item.isNew) {
    $store.dispatch('app/deleteItem', item)
    return
  }
  $store.dispatch('app/cancelEditItem', item)
}

function handleEdit(item: ApiDocItem) {
  $store.dispatch('app/editItem', item)
}

function handleDelete(item: ApiDocItem) {
  $store.dispatch('app/deleteItem', item)
}

function handleSelect(item: ApiDocItem) {
  $emit('select', item)
  visible.value = false
}

defineExpose({
  showModal() {
    visible.value = true
  }
})
</script>
<style lang="less">
.flex {
  display: flex;
  width: 100%;
}

.toolbar {
  padding-bottom: 20px;
  border-bottom: 1px solid #999;
  width: 100%;
}

.items-wrap {
  margin-top: 20px;
  width: 100%;
}

.item-card {
  margin-left: 20px;
  width: 380px;
}

.btn-ok {
  width: 300px;
}
</style>